package com.fhsk.file.manager.handler;

import com.fhsk.file.common.annotation.Token;
import com.fhsk.file.common.utils.jedis.JedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.UUID;


@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Resource
    JedisUtil jedisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Token annotation = method.getAnnotation(Token.class);
            if (annotation != null) {
                boolean needSaveSession = annotation.save();
                if (needSaveSession) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-","");
                    jedisUtil.set("token_" + uuid, "1", 60 * 60);
                    request.getSession().setAttribute("token", uuid);
                    log.warn(request.getServletPath() + "---->token:" + uuid);
                }
                boolean needRemoveSession = annotation.remove();
                if (needRemoveSession) {
                    if (isRepeatSubmit(request)) {
                        log.warn("please don't repeat submit,url:" + request.getServletPath());
                        boolean pass = annotation.pass();
                        request.getSession().setAttribute("token_pass_repeat", "true");
                        return pass;
                    }
                }
            }
            return true;
        } else {
            return true;
        }
    }

    private boolean isRepeatSubmit(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return true;
        }
        Long upCount = jedisUtil.decr("token_" + token);
        //如果对更新标记做减减操作后不等0,表示是重复提交
        if (upCount != 0) {
            jedisUtil.del("token_" + token);
            return true;
        } else {
            jedisUtil.del("token_" + token);
            return false;
        }
    }
}